layui.use(['table', 'admin', 'ax', 'func', 'upload', 'layer', 'laydate','form','formSelects'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var upload = layui.upload;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var form = layui.form;
    var formSelects = layui.formSelects;


    //渲染时间选择框
    laydate.render({
        elem: '#startTime'
    });
    //渲染时间选择框
    laydate.render({
        elem: '#endTime'
    });


    //渲染时间选择框
    laydate.render({
        elem: '#date',
        format:'yyyy-MM',
        value:new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth()),//默认上个月
        type: 'month',
        done:function(value,date,startDate){

        }
    });

    /**
     * 货赔表管理
     */
    var BtyCwHuopei = {
        tableId: "btyCwHuopeiTable"
    };

    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyCwHuopei/dmList");
    var languageResult = languageAjax.start();
    $.each(languageResult, function (index, val) {
        $("#shopName").append("<option value='" + val + "'>" + val + "</option>");
    });
    form.render('select');

    /**
     * 检索城市
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyCwHuopei/cityList");
    var languageResult = languageAjax.start();
    $.each(languageResult.data, function (index, val) {
        $("#provinceName").append("<option value='" + val.id + "'>" + val.city + "</option>");
    });
    form.render('select');

    form.on('select(provinceName)', function (data) {
        var provinceId = data.value;
        if (provinceId == "") {
            $("#cityName").html("");
            $("#cityName").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/btyCwHuopei/cityNameList");
            qyAjax.set("pid", provinceId);
            var qyResult = qyAjax.start();
            $("#cityName").html("");
            $("#cityName").append("<option value=''>全部</option>");
            $.each(qyResult.data, function (index, data) {
                $("#cityName").append("<option value='" + data.id + "'>" + data.simpleName + "</option>");
            });
            form.render('select');
        }
    });



    /**
     * 初始化表格的列
     */
    BtyCwHuopei.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'huopeiId', hide: true, title: '主键id'},
            {field: 'shopCode', hide: true, title: '门店编号'},
            {field: 'shopName', sort: true, title: '门店名称'},
            {field: 'turnover', sort: true, title: '营业额', align: 'center'},
            {field: 'priceSta', sort: true, title: '酒水卖价'},
            // {field: 'createUser', sort: true, title: '创建者'},
            // {field: 'createTime', sort: true, title: '创建时间'},
            // {field: 'num', sort: true, title: '序号'},
            {field: 'ywrq', align: "center", sort: false, title: '业务日期',width:200},
            // {field: 'beginTime', sort: true, title: '开始时间'},
            // {field: 'endTime', sort: true, title: '结束时间'},
            {field: 'heji', sort: true, title: '货赔合计', align: 'center'},
            {field: 'status', title: '状态', align: 'center'},

            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    BtyCwHuopei.search = function () {
        var queryData = {};
        queryData['shopName'] = $('#shopName').val();
        queryData['date'] = $('#date').val();
        queryData['priceSta'] = $('#priceSta').val();
        queryData['hpSta'] = $('#hpSta').val();
        queryData['provinceId'] = $('#provinceName').val();
        queryData['cityId'] = $('#cityName').val();
        table.reload(BtyCwHuopei.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    // 重置按钮事件
    $('#btnReset').click(function () {
        // $('input').val('');
        $('#startTime').val('');
        $('#endTime').val('');
        $("#scmCode").val('');
        $("#provinceName").val('');
        $("#cityName").val('');
        $("#shopName").val('');
        $("#priceSta").val('');
        $("#hpSta").val('');
        form.render();
    });

    /**
     * 点击同步酒水价格
     */
    BtyCwHuopei.btnEditJsNotice = function (data) {
        loadIndex = layer.load('正在导入...',2, { shade: [0.15, '#ccc'] });
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/editJsmj",
            datatype: "json",
            data: {"date":$('#date').val()},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("同步完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };


    /**
     * 点击同步货赔单价
     */
    BtyCwHuopei.btnEditPriceNotice = function (data) {
        loadIndex = layer.load('正在导入...',2, { shade: [0.15, '#ccc'] });
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/editPrice",
            datatype: "json",
            data: {"date":$('#date').val()},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("同步完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };


    /**
     * 点击计算货赔合计
     */
    BtyCwHuopei.btnEditHpNotice = function (data) {
        loadIndex = layer.load('正在计算...',2, { shade: [0.15, '#ccc'] });
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/editHp",
            datatype: "json",
            data: {"date":$('#date').val()},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("计算完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };

    /**
     * 点击发送门店
     */
    BtyCwHuopei.btnMsgNotice = function (data) {
        loadIndex = layer.load('正在计算...',2, { shade: [0.15, '#ccc'] });
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/sendMsg",
            datatype: "json",
            data: {"date":$('#date').val(),"provinceId":$('#provinceName').val(),"cityId":$('#cityName').val()},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("发送成功，有货赔合计的门店，已发送到店长的小妖中！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("发送失败！");
                layer.close(loadIndex);
            }
        });
    };

    /**
     * 获取货赔数据
     */
    BtyCwHuopei.btnSyncHpNotice = function (data) {
        loadIndex = layer.load('正在读取...',2, { shade: [0.15, '#ccc'] });
        var zxId = formSelects.value('scmCode', 'valStr');
        var zxId1 = zxId.split(",");
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/scmDetail",
            datatype: "json",
            data: {"startTime":$('#startTime').val(),"endTime":$('#endTime').val(),"storeIdList":zxId1},
            traditional: true,
            success: function (data) {
                if (data.success){
                    table.reload(BtyCwHuopei.tableId);
                    Feng.success("同步完成！");
                }else {
                    Feng.error("获取失败，" + data.message);
                }
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };

    /**
     * 获取门店货赔数据
     */
    BtyCwHuopei.btnSyncMdHpNotice = function (data) {
        loadIndex = layer.load('正在读取...',2, { shade: [0.15, '#ccc'] });
        var zxId = formSelects.value('scmCode', 'valStr');
        var zxId1 = zxId.split(",");
        if (zxId1 == "" || zxId1==undefined || zxId1==null) {
            Feng.error("请选择门店进行获取货赔数据!");
            layer.close(loadIndex);
            return;
        }
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/scmDetail",
            datatype: "json",
            data: {"startTime":$('#startTime').val(),"endTime":$('#endTime').val(),"storeIdList":zxId1},
            traditional: true,
            success: function (data) {
                if (data.success){
                    table.reload(BtyCwHuopei.tableId);
                    Feng.success("同步完成！");
                }else {
                    Feng.error("获取失败，" + data.message);
                }
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };

    /**
     * 同步单店酒水价格
     * @param data
     */
    BtyCwHuopei.editJsItem = function(data){
        var date = $("#date").val();
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/editDdjs",
            datatype: "json",
            data: {"date":$('#date').val(),"shopCode":data.shopCode},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("同步完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });

        // var index=layer.open({
        //     type: 2,
        //     title: false,
        //     content: Feng.ctxPath + '/btyCwHuopei/hpDetail?shopCode=' + data.shopCode + "&beginTime=" + data.beginTime + "&shopName=" + data.shopName + "&endTime=" + data.endTime,
        //     tableId: BtyCwHuopei.tableId
        // });
    };

    /**
     * 同步单店货赔价格
     * @param data
     */
    BtyCwHuopei.editHpItem = function(data){
        var date = $("#date").val();
        $.ajax({
            type: "PUT",
            url: "/btyCwHuopei/editDdhp",
            datatype: "json",
            data: {"date":$('#date').val(),"shopCode":data.shopCode},
            success: function (data) {
                table.reload(BtyCwHuopei.tableId);
                Feng.success("同步完成！");
                layer.close(loadIndex);
            }, error: function () {
                Feng.error("修改失败！");
                layer.close(loadIndex);
            }
        });
    };

    /**
     * 跳转到添加页面
     */
    BtyCwHuopei.jumpAddPage = function () {
        window.location.href = Feng.ctxPath + '/btyCwHuopei/add'
    };

    /**
    * 跳转到编辑页面
    *
    * @param data 点击按钮时候的行数据
    */
    BtyCwHuopei.jumpEditPage = function (data) {
        window.location.href = Feng.ctxPath + '/btyCwHuopei/edit?huopeiId=' + data.huopeiId
    };

    /**
     * 导出excel按钮
     */
    BtyCwHuopei.exportExcel = function () {
        var date = $('#date').val();
        var ajax = new $ax("/btyCwHuopei/export", function (data) {
        }, function (data) {
        });
        ajax.set("date", date);
        const result = ajax.start();
        table.exportFile(tableResult.config.id, result, 'xls');
    };

    BtyCwHuopei.expList = function () {
        var date = $('#date').val();
        if (date == "" || date == undefined || date == null) {
            Feng.error("请先选择日期");
        }else {
            var url = Feng.ctxPath + "/btyCwHuopei/exportBatch?date=" + date;
            location.href = url;
        }

    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BtyCwHuopei.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyCwHuopei/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(BtyCwHuopei.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("huopeiId", data.huopeiId);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 门店货赔情况
     */
    // BtyCwHuopei.costSetting = function (data) {
    //     window.location.href = Feng.ctxPath + '/btyCwHuopei/hpDetail?shopCode=' + data.shopCode + "&beginTime=" + data.beginTime + "&shopName=" + data.shopName + "&endTime=" + data.endTime;
    // };

    /**
     * 门店货赔情况弹窗
     */
    var shopCode;
    var endTime;
    var huopei;
    var turnover;
    BtyCwHuopei.costSetting = function(data){
        var date = $("#date").val();
        shopCode = data.shopCode;
        endTime = data.endTime;
        var index=layer.open({
            type: 2,
            title: false,
            content: Feng.ctxPath + '/btyCwHuopei/hpDetail?shopCode=' + data.shopCode + "&beginTime=" + data.beginTime + "&shopName=" + data.shopName + "&endTime=" + data.endTime,
            tableId: BtyCwHuopei.tableId,
            success: function(layero, index) {},
            cancel:function (layero, index) {//关闭按钮时操作
                var ajax = new $ax(Feng.ctxPath + '/btyCwHuopei/huopeiInfo?shopCode=' + data.shopCode + "&beginTime=" + data.beginTime + "&shopName=" + data.shopName + "&endTime=" + data.endTime);
                var result = ajax.start();
                huopei = result.data[result.data.length-2].thNum;
                turnover = result.data[0].turnover;
                data1.forEach(function (item, index) {
                    if (item.shopCode === shopCode && item.endTime === endTime) {
                        var td = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='heji'] div");
                        var td1 = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='turnover'] div");
                        td.text(huopei);
                        td1.text(turnover)
                    }
                })
            }
        });
        layer.full(index)
    };


    // 渲染表格
    var data1;
    var that;
    var tableResult = table.render({
        elem: '#' + BtyCwHuopei.tableId,
        url: Feng.ctxPath + '/btyCwHuopei/list',
        where:{date:new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth())},//默认上个月
        page: true,
        limit: 20,
        height: "full-129",
        cellMinWidth: 100,
        cols: BtyCwHuopei.initColumn(),
        done:function (res) {
            data1 = res.data;
            that = this.elem.next();
        }

    });

    /**
     * 导入Excel
     */
    var loadIndex;
    upload.render({
        elem: '#btnExcel'
        , url: '/btyCwHuopei/import'
        // , url: '/btyCwHuopei/addUsers'
        , accept: "file"
        , async: false
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        ,before: function(obj){//参数
            loadIndex = layer.load('正在导入...',2, { shade: [0.15, '#ccc'] });
        }
        , done: function (res) {
            if (res == true) {
                layer.msg('导入成功！', {icon: 1, time: 2000, shade: 0.2});
                layer.close(loadIndex);
                // window.location.reload();
                table.reload(BtyCwHuopei.tableId);
            }
            if (res.state == false) {
                layer.msg('导入失败！', {icon: 1, time: 2000, shade: 0.2});
                layer.close(loadIndex);
            }
        },
    });

    //同步酒水价格
    $('#btnEditJs').click(function () {
        BtyCwHuopei.btnEditJsNotice();
    });

    //同步货赔单价按钮
    $('#btnEditPrice').click(function () {
        BtyCwHuopei.btnEditPriceNotice();
    });

    //计算货赔合计
    $('#btnEditHp').click(function () {
        BtyCwHuopei.btnEditHpNotice();
    });

    //发送门店
    $('#btnMsg').click(function () {
        BtyCwHuopei.btnMsgNotice();
    });

    //获取货赔数据
    $('#btnSyncHp').click(function () {
        BtyCwHuopei.btnSyncHpNotice();
    });

    //获取门店货赔数据
    $('#btnSyncMdHp').click(function () {
        BtyCwHuopei.btnSyncMdHpNotice();
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BtyCwHuopei.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    BtyCwHuopei.jumpAddPage();

    });

    // 导出excel
    $('#btnExp').click(function () {
        BtyCwHuopei.exportExcel();
    });

    // 批量导出货赔
    $('#expList').click(function () {
        BtyCwHuopei.expList();
    });

    //初始化门店
    var languageAjax = new $ax(Feng.ctxPath + "/btyCwHuopei/scmName");
    var languageResult = languageAjax.start();
    $("#scmCode").html("");
    $.each(languageResult.data, function (index, val) {
        if(val.scmName != undefined) {

            $("#scmCode").append("<option value='" + val.scmCode + "'>" + val.scmName + "</option>");
        }
    });
    formSelects.render('scmCode');


    // 工具条点击事件
    table.on('tool(' + BtyCwHuopei.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            BtyCwHuopei.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            BtyCwHuopei.onDeleteItem(data);
        }else if (layEvent === 'detail') {
            BtyCwHuopei.costSetting(data);
        }else if (layEvent === 'editJs'){
            BtyCwHuopei.editJsItem(data);
        }else if (layEvent === 'editHp'){
            BtyCwHuopei.editHpItem(data);
        }
    });
});
